package com.example.gulimall.coupon.service.impl;

import com.example.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.example.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.coupon.dao.SeckillSessionDao;
import com.example.gulimall.coupon.entity.SeckillSessionEntity;
import com.example.gulimall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLates3DaySession() {
        List<SeckillSessionEntity> sessionEntityList = list(new QueryWrapper<SeckillSessionEntity>()
                .between("start_time", getStartTime(), getEndTime()));
        List<SeckillSessionEntity> sessionEntities = sessionEntityList.stream().map(item -> {
            List<SeckillSkuRelationEntity> skuRelationEntities = seckillSkuRelationService
                    .list(new QueryWrapper<SeckillSkuRelationEntity>()
                            .eq("promotion_session_id", item.getId()));
            item.setRelationEntityList(skuRelationEntities);
            return item;
        }).collect(Collectors.toList());
        return sessionEntities;
    }
    public String getStartTime(){
        LocalDate now=LocalDate.now();
        LocalDateTime localDateTime = now.atTime(LocalTime.MIN);
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
    public String getEndTime(){
        LocalDate now=LocalDate.now();
        LocalDateTime localDateTime = now.plusDays(2).atTime(LocalTime.MAX);
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}